<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="org.apache.shiro.SecurityUtils" %>
<%@ page import="com.topisv.tms.service.account.ShiroDbRealm.ShiroUser" %>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
<script type="text/javascript"> 
	var dataTables_unhandle; 

  	$(function() {
		$("#queryForm").validate(); 
		//$("#add").hide();
		
		//初始化日期选择框
		var now = new Date();
		var today=(now.getFullYear())+"/"+(now.getMonth()<10? "0"+(now.getMonth()+1):(now.getMonth()+1))+"/"+(now.getDate()<10? "0"+now.getDate():now.getDate());    
		$("#_dataRange").val(today+" - "+today);
		$("#_dataRange").daterangepicker({format: 'YYYY/MM/DD',dateLimit :{days : 31}});
		
		//初始化dataTables-待处理订单
	    dataTables_unhandle=$("#table_unhandle").dataTable({
           "bServerSide":true,
           "sAjaxSource":'${ctx}/v2/jdExpress/bindData_unhandle',
           "fnServerData": retrieveData_unhandle,
           
           "iDisplayLength": 10, //每页数据
           "bPaginate": true, //翻页功能
           "bLengthChange": true, //改变每页显示数据数量
           "bFilter": false, //过滤功能
           "bSort": false, //排序功能
           "bInfo": true,//页脚信息
           "bAutoWidth": true,//自动宽度
           "bStateSave": false, //状态保存，使用了翻页或者改变了每页显示数据数量，会保存在cookie中，下回访问时会显示上一次关闭页面时的内容
           "bProcessing": true, //加载数据时显示正在加载信息
           
           "aoColumns": [  //排序控制
				null,
				{ "asSorting": [ "asc" ] },
				{ "asSorting": [ "desc", "asc", "asc" ] }
			],
           
           "sZeroRecords": "查询无记录！",
           "oLanguage": { //汉化   
               "sUrl": '${ctx}/static/v2/js/plugins/datatables/cn.txt'
            },
            "aoColumns": [ 
					{
						"mData" : null,
						"mRender" : function(data, display, row) {
							var str = "<input type=\"checkbox\" name=\"alreadyMyChecked\" id=\"check_already"+row.id+"\" value="+row.id+" class=\"checkChosen icheckbox_minimal\" onclick=\"checkToggle(this,event);\"/>";
							return str;
						}
					},
                          
                    {"mData": null,
                    	 "mRender": function (data, display, row) {
		              		<c:forEach items="${customerList}" var="customer">
								if("${customer.customerCode}" == row.customerCode){
									return "${customer.customerName}";
								}
							</c:forEach>
							return "";
			           }
                    },
                    {"mData": 'warehouseCode'}, 
                    {
                      "mData": 'ordeno',
                      "render":function(obj){
                        return "<a href='${ctx}/orderMsg/v2_orderMsgDetail/"+obj+"' title='查看订单信息' target='_blank' class='checkInfo'>"+obj+"</a>";
                      }	
                    },
                    {"mData":'customerOrdeno'},
                    {"mData": 'shopna'},
                    {"mData": 'recena'},
                    {"mData": 'provna'},
                    {"mData": 'cacode'},
                    {
                      "mData": 'dispatchFlag',
                      "render": function (obj) {
                         return "1" == obj ? "是" : "否";
                      }
                    },
                    {
                      "mData": 'crtime',
                      "render": function (obj) {
                         var time=obj.time;
                         var date = new Date(time);
                         return date.Format("MM-dd hh:mm");
                      }
                    },
                    {
                     "mData": 'addres',
                     "render": function (obj,type,full) {
                    	var ret ="";
                    	ret = "<a href='#ordersDetail' onclick='getAjaxOrders("+full.id+")' class='btn btn-default btn-sm' role='button' data-toggle='modal' >订单详情</a>";
                        return ret+" <a href='#orderItemsDetail' onclick='getAjaxItems("+full.id+")' class='btn btn-default btn-sm' role='button' data-toggle='modal' >商品详情</a>";
                      }
                    }
             ]
        });

        $("#alreadyMyCheckedAll").iCheck({
			checkboxClass : 'icheckbox_minimal'
		});
		// 批量选中
		$("#alreadyMyCheckedAll").on("ifChecked", function(event) {
			var eachNum = 0;
			$('#table_unhandle .checkChosen').each(function() {
				$(this).iCheck('check');
				eachNum++;
				if (eachNum == 10) {
					return false;
				}
			});
		});
		$("#alreadyMyCheckedAll").on("ifUnchecked", function(event) {
			$('#table_unhandle .checkChosen').each(function() {
				$(this).iCheck('uncheck');
			});
		});
	});

	//查询
 	function query(){
	   //验证查询条件：
	   //商家：
	   var customerCode=$("#_customerCode").val();
	   
	   
	   //日期：
	   var dataRange=$("#_dataRange").val();
	   if(dataRange.length==0){
	      alert("请选择日期范围...");
	      return;
	   }
	
	   dataTables_unhandle.fnDraw();
	} 

	//回调函数_待处理订单
 	function retrieveData_unhandle( sSource, aoData, fnCallback ) {

	   //查询参数
	   var customerCode=$("#_customerCode").val();
	   aoData.push( { "name": "customerCode", "value": customerCode } );  
	    
	   var warehouseCode=$("#_warehouseCode").val();
	   aoData.push( { "name": "warehouseCode", "value": warehouseCode } );
	   
	   var dataRange=$("#_dataRange").val();
	   aoData.push( { "name": "dataRange", "value": dataRange } );
	   
	   $.ajax({ 
	       "type": "post",
	       "contentType": "application/json", 
	       "url": sSource,    
	       "dataType": "json",   
	       "data": JSON.stringify(aoData),
	       "success": function(resp) {  
	       			fnCallback(resp);
	       			$("#total_unhandle").html("("+resp.iTotalRecords+")");
	       		}
	   });    
	} 

	function add(){ 
		var nrName;
		var jdName;
		var j = 0;
		var objs = [];
		$('#modalContent tr').each(function() {
			jdName = $(this).find('.expressNo').val();
			if (jdName.length == 0) {
				j ++ ;
			}
		})

		if (j == 0) {
			$('#modalContent tr').each(function() {
				jdName = $(this).find('.expressNo').val();
				nrName = $(this).find('.orderNo').text();
				var obj = { 'name': nrName, 'value': jdName };
	                objs.push(obj);
			})
			$.ajax({
				"type": "post",
			    "contentType": "application/json", 
			    "url": '${ctx}/v2/jdExpress/addExpressNo',    
			    "dataType": "json",   
			    "data": JSON.stringify(objs), 
				/* {
					"expressNo[]":objs
				}, */
				success : function(data) {
				   alert(data.content);
				   for(i = 0; i < 10; i++){
					   $("#_expressNo" + i).val('');
				   }
				   window.location.href = "${ctx}/v2/jdExpress/v2_init";
				},
				error : function() {
					alert("添加京东快递单号失败！");
					for(i = 0; i < 10; i++){
						   $("#_expressNo" + i).val('');
					   }
					window.location.href = "${ctx}/v2/jdExpress/v2_init";
				}
			});
		}
		else {
			jAlert("还有京东单号未填写", "错误提示");
			return false;
		}
	} 

	function check(obj){
		var id = obj.id;
		var j = id.substring(id.length-1,id.length);
		var value = $(obj).val();
		var value2;
		var name;
		for(i = 0; i < 10; i++){
			if(i != j){
				name = "#_expressNo" + i;
				value2 = $(name).val();
				if(value == value2){
					alert("填入单号重复,请核对后重新填入.");
					$(obj).val('');
					$(obj).focus();
					return;
				}
			}
		}
		
		if(j == 9){
			name = "#_expressNo0";
		}else{
			name = Number(j) + Number(1);
			name = "#_expressNo" + name;
		}
		$(name).focus();
		
	} 

	function ajaxAreaGroup2(item,id) {
     	$("#"+id).html('');
		var customerCode=item.value;
		if(customerCode==''){
	  		return false;
		}
	
		$.ajax({
			type : 'post',
			url : '${ctx}/areaGroup/ajaxAreaGroup',
			data : 'customerCode=' + customerCode,
			dataType : 'json',
			success : function(data) {
			  var tempString="";
			  tempString+="<option value=''></option>";
				if (data.status == "1") {
					$.each(data.content,function(i){
					    tempString+="<option value="+data.content[i].groupCode+">"+data.content[i].groupName;
					});
				}else if (data.status == "2") {
					$.each(data.content.restAreaGroupDtos,function(i){
					    tempString+="<option value="+data.content.restAreaGroupDtos[i].areagroupCode+">"+data.content.restAreaGroupDtos[i].areagroupName;
					});
				} else {
					alert(data.content);
				}
                  $("#"+id).html(tempString);
                  $("#"+id).trigger("chosen:updated");
			},
			error : function() {
				alert("获取信息错误！");
			}
		}); 
	} 

	function checkToggle(_this,e) {
		// e.preventDefault();
		var checkNum = 0;
		$('#table_unhandle .checkChosen').each(function() {
			if ($(this).parent().attr("aria-checked") == "true") {
				checkNum ++;
			}
		});
		if (_this.parentElement.getAttribute("aria-checked") == "true") {
			_this.parentElement.setAttribute("aria-checked", 'false');
		}
		else {
			if (checkNum == 10) {
				e.preventDefault();
				jAlert("选中的数量大于10", "错误提示");
				return false;
				_this.parentElement.setAttribute("aria-checked", 'false');
			}
			else {
				_this.parentElement.setAttribute("aria-checked", 'true');
			}
		}
	}

	// 判断是否有选中打开摸态框
	function openExpress() {
		$('#modalContent').empty();
		var checkNum = 0;
		var itemNum = 1;
		$('#table_unhandle .checkChosen').each(function() {
			if ($(this).parent().attr("aria-checked") == "true") {
				checkNum ++;
				return;
			}
		});
		if (checkNum == 0) {
			jAlert("请先选择记录!", "错误提示");
			return false;
		}
		else if (checkNum > 10) {
			jAlert("选中的数量大于10", "错误提示");
			return false;
		}
		else{
			var modalStr = '';
			$('#table_unhandle .checkChosen').each(function() {
				if ($(this).parent().attr("aria-checked") == "true") {
					var itemVal = $(this).parent().siblings().find(".checkInfo").text();
					modalStr += '<tr>'
						      	+'<td>'+itemNum+'</td>'
						      	+'<td class="orderNo" name="_orderNo'+itemNum+'" maxlength=30>'+itemVal+'</td>'
						      	+'<td><input type="text" class="form-control span expressNo" name="_expressNo'+itemNum+'" maxlength=30 onchange="check(this)" required></td>'
					      	+'</tr>';
					itemNum ++ ;
				}
			})
			$("#modalContent").append(modalStr);
			$('#express').modal('show');
		}
	}
</script>
</head>

<body>
<div id="fullbg"></div>
<div id="dialog">
	<div>
		<img src="${ctx }/static/022.gif"></img>
	</div>
</div>

<section class="content">
    <!-- 查询条件  start-->
   	<div class="row">
	<div class="col-md-12">
			<!-- Primary box -->
			<div class="box box-solid box-primary" >
			    
				<div class="box-header">
					<i class="fa fa-search"></i>
					<h3 class="box-title">搜索栏</h3>
				</div>
				
				<div class="box-body">
				    <form class="form-search" id="queryForm" method="post" >
				    <!-- 第一行 -->
					<div class="form-group row">
					
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 商家： </span> 
								<select data-placeholder="请选择..." class="form-control searchSelect" id="_customerCode" name="_customerCode" onchange="ajaxAreaGroup2(this,'_warehouseCode')">
									<option value=""></option>
									<c:forEach items="${customerList}" var="customer">
										<option value="${customer.customerCode}"
											<c:if test="${customerCode eq customer.customerCode}">selected=selected</c:if>>${customer.customerName}</option>
									</c:forEach>
								</select>
							</div>
						</div>
						
						<div class="col-sm-3">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 仓库： </span> 
								<select class="form-control span3" id="_warehouseCode" name="_warehouseCode">
									<option value=""></option>
									<c:forEach items="${warehouseList}" var="warehouse">
										<option value="${warehouse.groupCode}" >${warehouse.groupName}</option>
									</c:forEach>
								</select>
							</div>
						</div>
						
					</div>

                    <!-- 第二行 -->
					<div class=" form-group row">

						<div class="col-sm-6">
							<div class="input-textgroup col-sm-12">
								<span class="input-group-text"> 日期范围： </span>

								<div class="input-group">
									<div class="input-group-addon">
										<i class="fa fa-calendar"></i>
									</div>
									<input type="text" class="form-control pull-right" id="_dataRange" name="_dataRange" value="${param._fromDate}"/>
								</div>
								
							</div>
						</div>
						
					</div>
					 <!-- 第三行 -->
					<div class=" form-group row">
						<div class="col-sm-3">
								<button class="btn btn-primary" type="button" onclick="query();">搜索</button>
								<a id="add" href='#express' class='btn btn-primary' role='button' onclick="openExpress();">添加京东单号</a>
						</div>
					</div>
					</form>
				</div>

			</div>

	 </div>
	</div>
	
	<div class="form-group row" >
	<div class="col-md-12">
		<div class="box box-primary">
			<div class="box-header"></div>
				<div class="box-body">
					<table id="table_unhandle" class="table table-striped table-bordered table-condensed">
						 <thead>
							<tr>
							 	<th style="width: 30px;">
							 		<input type="checkbox" name="alreadyMyCheckedAll" id="alreadyMyCheckedAll"/></th>
							    <th style="width: 60px;">商家</th>
							    <th style="width: 20px;">仓库</th>
								<th style="width: 100px;">能容订单号</th>
								<th style="width: 100px;">客户订单号</th>
								<th style="width: 80px;">来源店铺</th>
								<th style="width: 50px;">收货人</th>
								<th style="width: 50px;">目的地</th>
								<th style="width: 50px;">快递公司</th>
								<th style="width: 30px;">可处理</th>
								<th style="width: 60px;">审单时间 </th>
								<th style="width: 100px;">查询操作</th>
							 </tr>
						 </thead>
					</table>
				</div>
			  </div>
           </div>
	    </div>
	<!-- 查询结果 end -->
	
	<!-- 弹出窗体-商品详情 start  -->
	<div id="ordersDetail" class="modal fade">
		<div class="modal-dialog" style="width: 60%;">
			<div class="modal-content">
			
				<div class="modal-body">
					<div class="box box-solid box-primary">
			      		<div class="box-header"><span class="box-title">订单详细信息</span></div>
						<div class="box-body">
							<table class="table table-striped table-bordered table-condensed" id="modalBodyOrders"></table>
						</div>
					</div>
				</div>
				
			</div>	
		</div>
	</div>
	<!-- 弹出窗体-商品详情 end  -->
	
	<!-- 弹出窗体-订单详情 start  -->
	<div id="orderItemsDetail" class="modal fade">
		<div class="modal-dialog" style="width: 60%;">
			<div class="modal-content">
			
				<div class="modal-body">
					<div class="box box-solid box-primary">
			      		<div class="box-header"><span class="box-title">订单详细信息</span></div>
						<div class="box-body">
							<table class="table table-striped table-bordered table-condensed" id="modalBodyItems"></table>
						</div>
					</div>
				</div>
				
			</div>	
		</div>
	</div>
	<!-- 弹出窗体-订单详情 end  -->
	
	 <div id="express" class="modal fade">
		<div class="modal-dialog" style="width: 40%;">
			<div class="modal-content">
				<div class="modal-body">
					<div class="box box-solid box-primary">
			      		<div class="box-header"><span class="box-title">添加京东单号</span></div>
			      		<div class="box-body" align="center">
			      			<table class="table table-striped table-bordered table-condensed">
			      				<thead>
			      					<th>序号</th>
			      					<th>能容订单号</th>
			      					<th>京东快递单号</th>
			      				</thead>
			      				<tbody class="text-center" id="modalContent">
			      					
			      				</tbody>
			      			</table>
			      			<div>
								<button class="btn btn-primary" type="button" style="margin-top:20px;" onclick="add();">确认添加</button>
							</div>
						</div>
					</div>
				</div>
			</div>	
		</div>
	</div> 
	
	</section>
</body>
</html>